package io.wins.vertx.verticle.api;

import io.vertx.core.Future;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.wins.vertx.entity.Comment;
import io.wins.vertx.service.CommentService;
import org.apache.commons.lang3.StringUtils;

public class CommentApiVerticle extends RestApiVerticle {

    public static final String REST_ADDRESS = "io.wins.rest.comment#%1$s";
    private static final Logger logger = LoggerFactory.getLogger(CommentApiVerticle.class);

    public final CommentService service;

    public CommentApiVerticle(final CommentService commentService) {
        this.service = commentService;
    }

    @Override
    public void start(final Future<Void> startFuture) throws Exception {
        super.start();
        this.on(String.format(REST_ADDRESS, CREATE), this::createComment);
        this.on(String.format(REST_ADDRESS, LIST), this::listComment);
        this.on(String.format(REST_ADDRESS, UPDATE), this::reviewComment);
        this.on(String.format(REST_ADDRESS, DELETE), this::deleteComment);
        startFuture.complete();
    }

    private void deleteComment(final Message<JsonObject> tMessage) {
        final String id = tMessage.body().getJsonObject("param").getString("id");
        this.service.deleteComment(id, tMessage);
    }

    private void reviewComment(final Message<JsonObject> tMessage) {
        final JsonArray ids = tMessage.body().getJsonObject("body").getJsonArray("ids");
        final int status = tMessage.body().getJsonObject("body").getInteger("status");
        this.service.reviewComment(ids, status, tMessage);
    }

    private void listComment(final Message<JsonObject> tMessage) {
        final JsonObject param = tMessage.body().getJsonObject("param");
        final String concertId = param.getString("concertId");
        final String customerId = param.getString("customerId");
        if (!StringUtils.isEmpty(concertId) && !StringUtils.isEmpty(customerId)) {
            this.service.getCommentByConcertId(customerId, concertId, tMessage);
        } else {
            this.service.listComment(tMessage);
        }
    }

    private void createComment(final Message<JsonObject> tMessage) {
        final JsonObject body = tMessage.body().getJsonObject("body").getJsonObject("comment");
        final Comment comment = new Comment(body);
        System.out.println(comment.toJson());
        this.service.createComment(comment, tMessage);
    }
}
